//
//  WZQuestionController.m
//  ETong
//
//  Created by wanzhao on 15/10/30.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZQuestionController.h"
#import "WZQuestionFrame.h"
#import "WZQuestionCell.h"
#import "MBProgressHUD+WZ.h"
#import "MJRefresh.h"
#import "WZQuestionDetailController.h"
#import "WZSearchBar.h"
#import "WZSearchController.h"
#import "NetWorkShare.h"
#import "MBProgressHUD+WZ.h"
#import "IMSearchDisplayController.h"

@interface WZQuestionController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) WZSearchBar *searchBar;
@property (nonatomic, weak) UIButton *coverButton;
@property (nonatomic, assign) NSInteger pageNO;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger totalePage;
@property (nonatomic, weak) UIImageView *failedImageView;

@property (nonatomic, strong) NSMutableArray *searchDataArray;
@property (nonatomic, strong) IMSearchDisplayController *searchController;
@property (nonatomic, strong) UITableView *searchResultTableView;
@end

@implementation WZQuestionController


- (void)dealloc
{
    NSLog(@"WZQuestionController dealloc");
}

- (IMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[IMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        
        // searchResultsDataSource 就是 UITableViewDataSource
        _searchController.searchResultsDataSource = self;
        // searchResultsDelegate 就是 UITableViewDelegate
        _searchController.searchResultsDelegate = self;
        _searchController.delegate = self;
        _searchController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
        _searchController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
        _searchController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;

    }
    return _searchController;
}
#pragma mark 懒加载

- (NSMutableArray *)searchDataArray
{
    if (_searchDataArray == nil) {
        _searchDataArray = [NSMutableArray array];
    }
    return _searchDataArray;
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (WZSearchBar *)searchBar
{
    if (_searchBar == nil) {
        _searchBar = [[WZSearchBar alloc] init];
        _searchBar.frame = CGRectMake(0, 0, self.view.width, OppositeHeightRate(50));
        _searchBar.scopeBarBackgroundImage = [UIImage strechingWithImageName:@"acm_inputbox"];
        _searchBar.backgroundImage = [UIImage strechingWithImageName:@"toumingbeijing"];
        _searchBar.placeholder = @"搜索";
        _searchBar.delegate = self;
        [_searchBar setImage:[UIImage imageNamed:@"icon_search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        
    }
    return _searchBar;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xeeeeee);
    self.navigationItem.title = @"问题解答";
   
    //创建搜索框
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = ClearColor;
    headerView.frame = CGRectMake(0, 0, self.view.width, OppositeHeightRate(51));
    [self.view addSubview:headerView];
    
    [headerView addSubview:self.searchBar];
    
    
    UIView *line1 = [[UIView alloc] init];
    line1.frame = CGRectMake(0, CGRectGetMaxY(_searchBar.frame), self.view.width, OppositeHeightRate(0.5));
    line1.backgroundColor = RGBCOLORWITH16COLOR(0xffffff);
    [headerView addSubview:line1];
    
    
    UIView *line2 = [[UIView alloc] init];
    line2.frame = CGRectMake(0, CGRectGetMaxY(line1.frame), self.view.width, OppositeHeightRate(0.5));
    line2.backgroundColor = RGBCOLORWITH16COLOR(0xd4d4d4);
    [headerView addSubview:line2];

//    [self searchController];
    
    //创建数据加载失败页面
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame), self.view.width, HARDWARE_SCREEN_HEIGHT - 64 - CGRectGetMaxY(headerView.frame))];
//    imageView.image = [UIImage imageNamed:@"loadFailedImage"];
//    imageView.hidden= YES;
//    [self.view addSubview:imageView];
//    self.failedImageView = imageView;
    
    //创建数据table
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame), self.view.width, HARDWARE_SCREEN_HEIGHT - 64 - CGRectGetMaxY(headerView.frame)) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ClearColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    
    //创建搜索结果table
    
    //创建搜索结果table
    UITableView *searchResultTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame), self.view.width, HARDWARE_SCREEN_HEIGHT - 64 - CGRectGetMaxY(headerView.frame)) style:UITableViewStyleGrouped];
    searchResultTableView.tag = 444444;
    searchResultTableView.backgroundColor = WhiteColor;
    searchResultTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    searchResultTableView.showsHorizontalScrollIndicator = NO;
    searchResultTableView.showsVerticalScrollIndicator = NO;
    searchResultTableView.scrollEnabled = YES;
    searchResultTableView.dataSource = self;
    searchResultTableView.delegate = self;
    searchResultTableView.hidden = YES;
    [self.view addSubview:searchResultTableView];
    [self.view sendSubviewToBack:searchResultTableView];
    self.searchResultTableView = searchResultTableView;
    
    
    //创建覆盖层
    UIButton *coverButton = [UIButton buttonWithType:UIButtonTypeCustom];
    coverButton.tag = 333333;
    coverButton.backgroundColor = RGBACOLORWithAlpha(0, 0, 0, 0.6f);
    coverButton.frame = CGRectMake(0,  CGRectGetMaxY(headerView.frame), HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64 - CGRectGetMaxY(headerView.frame));
    [coverButton addTarget:self action:@selector(cancelSearch) forControlEvents:UIControlEventTouchUpInside];
    coverButton.hidden = YES;
    [self.view addSubview:coverButton];
    [self.view sendSubviewToBack:coverButton];

    //给当前页以及每页的条数赋初始值
    self.pageNO = 1;
    self.pageSize = 20;
    self.totalePage = NSIntegerMax;
    
    __weak __typeof(self) weakSelf = self;
    
    //增加下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDataWithTitle:@""];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    //增加上拉加载更多
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [weakSelf loadMoreDataWithTitle:@""];
    }];
    [footer setTitle:@"加载更多..." forState:MJRefreshStateRefreshing];
    
    
    self.tableView.footer = footer;
    [self loadMBDataWithTitle:@""];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}

- (void)loadMBDataWithTitle:(NSString *)title
{
    self.pageNO = 1;
    self.totalePage = NSIntegerMax;
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    [NetWorkShare getQuestionListWithQuestionTitle:title pageNO:[NSString stringWithFormat:@"%zd",self.pageNO] pageSize:[NSString  stringWithFormat:@"%zd",self.pageSize] successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showSuccess:@"更新成功"];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSDictionary *infoDic = responseObject[@"pageInfo"];
                self.totalePage = [infoDic[@"total"] integerValue];
                self.pageNO = [infoDic[@"pageNo"] integerValue];
                self.pageSize = [infoDic[@"pageSize"] integerValue];
                [self.dataArray removeAllObjects];
                if ([infoDic[@"list"] isKindOfClass:[NSArray class]]) {
                    NSArray *array = [WZQuestion objectArrayWithKeyValuesArray:infoDic[@"list"]];
                    for (WZQuestion *question in array) {
                        WZQuestionFrame *quesFrame = [[WZQuestionFrame alloc] init];
                        quesFrame.question = question;
                        [self.dataArray addObject:quesFrame];
                    }
                    
                    [self.tableView reloadData];
                }
                
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"网络异常"];
    }];
}


- (void)loadDataWithTitle:(NSString *)title
{
    self.pageNO = 1;
    self.totalePage = NSIntegerMax;
    
    [NetWorkShare getQuestionListWithQuestionTitle:title pageNO:[NSString stringWithFormat:@"%zd",self.pageNO] pageSize:[NSString  stringWithFormat:@"%zd",self.pageSize] successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        [self.tableView.header endRefreshing];
        [MBProgressHUD showSuccess:@"更新成功"];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSDictionary *infoDic = responseObject[@"pageInfo"];
                self.totalePage = [infoDic[@"total"] integerValue];
                self.pageNO = [infoDic[@"pageNo"] integerValue];
                self.pageSize = [infoDic[@"pageSize"] integerValue];
                [self.dataArray removeAllObjects];
                if ([infoDic[@"list"] isKindOfClass:[NSArray class]]) {
                    NSArray *array = [WZQuestion objectArrayWithKeyValuesArray:infoDic[@"list"]];
                    for (WZQuestion *question in array) {
                        WZQuestionFrame *quesFrame = [[WZQuestionFrame alloc] init];
                        quesFrame.question = question;
                        [self.dataArray addObject:quesFrame];
                    }
                    
                    [self.tableView reloadData];
                }
                
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        [self.tableView.header endRefreshing];
        [MBProgressHUD showError:@"网络异常"];
    }];
}



- (void)loadMoreDataWithTitle:(NSString *)title
{
    
    if (self.pageNO >= self.totalePage) {
        [self.tableView.footer endRefreshing];
        [MBProgressHUD showError:@"没有更多数据"];
        return;
    }
    
    self.pageNO ++;
    [NetWorkShare getQuestionListWithQuestionTitle:title pageNO:[NSString stringWithFormat:@"%zd",self.pageNO] pageSize:[NSString  stringWithFormat:@"%zd",self.pageSize] successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self.tableView.footer endRefreshing];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSDictionary *infoDic = responseObject[@"pageInfo"];
                self.totalePage = [infoDic[@"total"] integerValue];
                self.pageNO = [infoDic[@"pageNo"] integerValue];
                self.pageSize = [infoDic[@"pageSize"] integerValue];
                if ([infoDic[@"list"] isKindOfClass:[NSArray class]]) {
                    NSArray *array = [WZQuestion objectArrayWithKeyValuesArray:infoDic[@"list"]];
                    for (WZQuestion *question in array) {
                        WZQuestionFrame *quesFrame = [[WZQuestionFrame alloc] init];
                        quesFrame.question = question;
                        [self.dataArray addObject:quesFrame];
                    }
                    
                    
                    
                    [self.tableView reloadData];
                }
                
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }

    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self.tableView.footer endRefreshing];
        [MBProgressHUD showError:@"网络异常"];
    }];
}

- (void)loadSearchDataWithTitle:(NSString *)title
{
    
    [MBProgressHUD showMessage:nil toView:self.view];
    
    [NetWorkShare getQuestionListWithQuestionTitle:title pageNO:@"1" pageSize:[NSString  stringWithFormat:@"%zd",NSIntegerMax] successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSDictionary *infoDic = responseObject[@"pageInfo"];
                if ([infoDic[@"list"] isKindOfClass:[NSArray class]]) {
                    NSArray *array = [WZQuestion objectArrayWithKeyValuesArray:infoDic[@"list"]];
                    for (WZQuestion *question in array) {
                        WZQuestionFrame *quesFrame = [[WZQuestionFrame alloc] init];
                        quesFrame.question = question;
                        [self.searchDataArray addObject:quesFrame];
                    }
                    
                    [self.searchResultTableView reloadData];
                }
                
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
               [self.searchResultTableView reloadData];            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
           [self.searchResultTableView reloadData];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"网络异常"];
        [self.searchResultTableView reloadData];
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _tableView) {
        return self.dataArray.count;
    } else {
        return self.searchDataArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZQuestionCell *queCell = [WZQuestionCell questionCellWithTableView:tableView];
    WZQuestionFrame *queFrame = nil;
    if (tableView == _tableView) {
        queFrame = self.dataArray[indexPath.row];
        queCell.queFrame = queFrame;
    } else {
        queFrame = self.searchDataArray[indexPath.row];
        queCell.queFrame = queFrame;
    }
    
    return queCell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.tableView == tableView) {
        UIView *SecView = [[UIView alloc] init];
        SecView.backgroundColor = ClearColor;
        
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(OppositeWidthRate(10), 0, HARDWARE_SCREEN_WIDTH - OppositeWidthRate(20), OppositeHeightRate(30));
        label.font = Font12;
        label.text = @"热门问题";
        label.textColor = RGBCOLORWITH16COLOR(0x999999);
        [SecView addSubview:label];
        return SecView;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.tableView == tableView) {
        
        return OppositeHeightRate(30);
    } else {
        return 0.01f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView) {
        WZQuestionFrame *queFrame = self.dataArray[indexPath.row];
        return queFrame.cellHeight;

    } else {
        WZQuestionFrame *queFrame = self.searchDataArray[indexPath.row];
        return queFrame.cellHeight;
  
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZQuestionFrame *queFrame = nil;
    if (tableView == _tableView) {
      queFrame  = self.dataArray[indexPath.row];
    } else {
        queFrame = self.searchDataArray[indexPath.row];
    }
   
    WZQuestionDetailController *vc = [[WZQuestionDetailController alloc] init];
    vc.questionId = queFrame.question.questionId;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark searchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    for (UIView *sub in searchBar.subviews) {
        for (UIView *su in sub.subviews) {
            if ([su isKindOfClass:[UIButton class]]) {
                UIButton *btn = (UIButton *)su;
                [btn setTitleColor:RGBCOLORWITH16COLOR(0x2f93e7) forState:UIControlStateNormal];
            }
            
        }
    }
    
    UIButton *coverButton = (UIButton *)[self.view viewWithTag:333333];
    UITableView *tableView = (UITableView *)[self.view viewWithTag:444444];
    
    if (searchBar.text.length > 0) {
        tableView.hidden = NO;
        [self.view bringSubviewToFront:tableView];
        
        coverButton.hidden= YES;
        [self.view sendSubviewToBack:coverButton];
    } else {
        coverButton.hidden = NO;
        [self.view bringSubviewToFront:coverButton];
        
        tableView.hidden = YES;
        [self.view sendSubviewToBack:tableView];
    }

    return YES;
}
#pragma mark searchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
//    searchBar.showsCancelButton = YES;
    
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self.searchDataArray removeAllObjects];
    [self loadSearchDataWithTitle:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    UIButton *coverButton = (UIButton *)[self.view viewWithTag:333333];
    UITableView *tableView = (UITableView *)[self.view viewWithTag:444444];
    if (searchBar.text.length > 0) {
        tableView.hidden = NO;
        [self.view bringSubviewToFront:tableView];
        
        coverButton.hidden= YES;
        [self.view sendSubviewToBack:coverButton];
    } else {
        coverButton.hidden = NO;
        [self.view bringSubviewToFront:coverButton];
        
        tableView.hidden = YES;
        [self.searchDataArray removeAllObjects];
        [tableView reloadData];
        [self.view sendSubviewToBack:tableView];
    }
    
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self cancelSearch];
}

- (void)cancelSearch
{
    self.searchBar.showsCancelButton = NO;
    [self.searchBar resignFirstResponder];
    self.searchBar.text = @"";
    UITableView *tableView = (UITableView *)[self.view viewWithTag:444444];
    if (tableView) {
        tableView.hidden = YES;
        [self.view sendSubviewToBack:tableView];
    }
    
    UIButton *coverButton = (UIButton *)[self.view viewWithTag:333333];
    if (coverButton) {
        coverButton.hidden = YES;
        [self.view sendSubviewToBack:coverButton];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
}
@end
